<template>
  <!-- 人员弹窗 -->
  <a-modal
    centered
    :title="headerTitle"
    :visible.sync="dialogVisible"
    okText=""
    @cancel="handleCancel"
    @ok="handleConfirm"
    width="1200px"
  >
    <a-row :gutter="10">
      <!-- <a-col v-if="address" :span="24" class="mb20">
        {{ address }}
      </a-col> -->
      <!-- 侧边栏 -->
      <a-col
        v-if="needTree"
        :span="6"
        style="border-right: 1px solid #d9d9d9"
      >
        <!-- 公司组织树搜索 -->
        <tree-organization
          v-if="dialogVisible"
          ref="treeOrganization"
          @loader="search"
          :autoSelect="false"
          :expandByAuto="true"
          :projectDeptOrgId="projectDeptOrgId"
          :selectedKeys.sync="selectedKeys"
          :selectOptions.sync="selectOptions"
        />
      </a-col>
      <!-- 主内容 -->
      <a-col :span="needTree ? 18 : 24">
        <!-- 搜索 -->
        <searchData
          class="member-search"
          :showTitleName="false"
          :searchData="searchArr"
          @search="search"
        ></searchData>
        <!-- <a-input-search
                    v-model="nameLike"
                    placeholder="请输入员工名称"
                    class="mb12"
                    :maxLength="30"
                    @search="search"
                ></a-input-search>
                <div style="maxHeight:150px;overflow:auto">
                    <a-tag
                        class="mb20"
                        v-for="(person, index) in persons"
                        :key="person.id"
                        closable
                        @close="() => handleClose(person, index)"
                        color="#108ee9"
                        >{{ person.name }}</a-tag
                    >
                </div> -->

        <!-- <a-button
                    :disabled="rowSelection.selectedRowKeys.length < 1"
                    type="primary"
                    icon="plus"
                    @click="handleAddMore"
                    >批量添加</a-button
                > -->
        <!-- 表格 -->
        <s-table
          v-if="dialogVisible"
          ref="table"
          :scroll="{ y: 400 }"
          tableLayout="fixed"
          size="default"
          :rowKey="(row) => row.id || row.employeeId"
          :columns="columns"
          :row-selection="rowSelection"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          @onSelect="handleSubmit"
          showPagination="auto"
        >
          <span
            slot="postPNames"
            slot-scope="text"
          >
            <div
              class="ellipsis"
              :title="filterPostPName(text)"
            >{{ filterPostPName(text) }}</div>
          </span>
          <!-- 表格操作栏 -->
          <span
            slot="actions"
            slot-scope="text, record"
          >
            <template>
              <a
                @click="handleSubmit(record)"
                :disabled="record.isAdd"
              >{{
                                record.isAdd ? '已添加' : '添加'
                            }}</a>
            </template>
          </span>
        </s-table>

        <template>
          <a-form-model
            class="flex-model-form"
            ref="addForm"
            :model="addForm"
            :rules="addRules"
          >
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-model-item
                  label="入团时间"
                  prop="leagueTime"
                >
                  <a-date-picker
                    v-model="addForm.leagueTime"
                    format="YYYY-MM-DD"
                    valueFormat="YYYY-MM-DD"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="团费缴至时间"
                  prop="duesEndTime"
                >
                  <a-date-picker
                    v-model="addForm.duesEndTime"
                    format="YYYY-MM-DD"
                    valueFormat="YYYY-MM-DD"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </template>
      </a-col>
    </a-row>
    <!-- 页脚操作栏 -->
    <div
      slot="footer"
      class="btn_box"
    >
      <a-button
        :disabled="addFormoading"
        key="back"
        @click="handleCancel"
      >
        取消
      </a-button>
      <a-button
        key="submit"
        type="primary"
        :loading="addFormoading"
        @click="submitForm"
      >
        确定添加
      </a-button>
      <!-- <a-button type="primary" @click="handleCancel">关闭</a-button> -->
    </div>
  </a-modal>
</template>

<script>
import { STable } from '@/components' // 表格
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import { getOrgsTree } from '@/api/subassembly/TreeSelectOrganization'
import { getPartyMemberByUserOrgId, addYouthMember } from '@/api/partyMasses/leagueManage'
const searchArr = [
  // 搜索框
  {
    name: '名称',
    type: 'input',
    value: 'nameLike'
  },
  {
    name: '员工编号',
    value: 'jobNumLike',
    type: 'input'
  },
  {
    name: '电话',
    value: 'phoneLike',
    type: 'input'
  }
]
export default {
  name: 'a' + Date.now(),
  // name: 'AddMember',
  components: {
    STable,
    TreeOrganization
  },
  props: {
    // 显隐控件
    visible: {
      type: Boolean,
      default() {
        return false
      }
    },
    projectDeptOrgId: {
      type: String,
      default() {
        return ''
      }
    },
    address: {
      type: String,
      default() {
        return ''
      }
    },
    // 表单
    form: {
      type: Object,
      default() {
        return {}
      }
    },
    // 标题
    headerTitle: {
      type: String,
      default() {
        return '选择人员'
      }
    },
    // 列表api
    api: {
      type: Object,
      default() {
        return {}
      }
    },
    // 列表api请求axios
    loadList: {
      type: String,
      default() {
        return 'getList'
      }
    },
    persons: {
      type: Array,
      default() {
        return []
      }
    },
    // 是否显示组织树
    needTree: {
      type: Boolean,
      default: () => true
    },
    curOption: {
      type: Object,
      default() {
        return null
      }
    }
  },
  computed: {
    // 树节点api
    apiTree() {
      return { getOrgsTree }
    },
    // 与父组件绑定visible
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (e) {
        this.$emit('update:visible', e)
      }
    },
    // 表格列表请求参数
    args() {
      let args = {}
      // 添加树节点id
      if (this.selectedKeys.length > 0) {
        args.rootOrgId = this.selectedKeys[0]
      }
      // 若表单不为空
      if (Object.keys(this.form)?.length) {
        Object.assign(args, this.form)
      }
      // 若关键词存在
      // this.nameLike && (args.nameLike = this.nameLike)
      if (Object.keys(this.queryParam)?.length) {
        Object.assign(args, this.queryParam)
      }
      return args
    }
  },
  data() {
    return {
      searchArr,
      queryParam: {},
      nameLike: '',
      selectedKeys: {},
      // 表格复选框配置
      rowSelection: {
        selectedRowKeys: [],
        type: 'radio',
        onChange(selectedRowKeys, selectedRows) {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        },

        getCheckboxProps: (record) => ({
          props: {
            disabled: record.disabled
          }
        })
      },
      loadData: (parameter) => {
        // if (this.args.orgId) {
        const requestParameters = Object.assign({}, parameter, this.args)
        requestParameters.pageNumber = requestParameters.pageNo
        return getPartyMemberByUserOrgId(requestParameters).then((res) => {
          let obj = {}
          obj.currentPage = requestParameters.pageNo
          obj.pageSize = requestParameters.pageSize
          obj.totalPage = Math.ceil(res.data.total / requestParameters.pageSize)
          obj.totalSize = res.data.total
          obj.data = res.data.list
          obj.data.forEach((item) => {
            item.isAdd = false
            this.persons?.forEach((i) => {
              if (item.userId == i.userId) {
                item.isAdd = true
                Object.assign(i, item)
              }
            })
          })
          return obj
        })
        // }
      },
      columns: [
        {
          title: '序号',
          width: 60,
          dataIndex: 'index',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '员工名称',
          dataIndex: 'name',
          customRender(text, record, index) {
            return record.disabled ? record.name + '(' + record.youthOrgName + ')' : text
          }
          // width: '25%',
        },
        {
          title: '员工编号',
          dataIndex: 'jobNum'
          // width: '25%',
        },
        {
          title: '电话号码',
          dataIndex: 'phoneNum'
          // width: '25%',
        },

        {
          title: '职务',
          ellipsis: true,
          dataIndex: 'postPNames',
          customRender(text, record, index) {
            return record.postPNames || '-'
          }
        }

        // {
        //     title: '操作',
        //     dataIndex: 'actions',
        //     width: '100px',
        //     scopedSlots: { customRender: 'actions' },
        // },
      ],
      selectOptions: {},
      addFormoading: false,
      addForm: {
        leagueTime: '',
        duesEndTime: ''
      },
      addRules: {
        leagueTime: [{ required: true, message: '请选择入团时间', trigger: 'change' }],
        duesEndTime: [{ required: true, message: '请选择团费缴至时间', trigger: 'change' }]
      }
    }
  },
  methods: {
    handleClose(removedPerson, index) {
      this.persons.splice(index, 1)
      this.$refs.table.loadData()
    },
    handleConfirm() {
      this.handleCancel()
      this.$emit('confirm', this.persons)
    },
    filterPostPName(val) {
      if (val === null) return ''
      return (
        val.reduce &&
        val.reduce((pre, cur) => {
          return pre === '' ? cur : pre + '、' + cur
        }, '')
      )
    },
    handleAddMore() {
      let list = []
      this.rowSelection.selectedRows.forEach((item) => {
        if (!item.isAdd) {
          item.isAdd = true
          list.push(item)
        }
      })
      this.$refs.table.loadData()
      list.forEach((item) => {
        this.persons.push(item)
      })

      // this.$emit('confirms', list)
    },
    // 头部搜索
    search(value) {
      if (value) {
        this.queryParam = {
          ...value
        }
      }
      this.$refs.table.refresh(true)
    },
    handleSubmit(record) {
      record.isAdd = true
      this.$refs.table.loadData()
      this.persons.push(record)
      // that.$emit('confirm', record)
    },
    handleCancel() {
      this.dialogVisible = false
    },
    confirmSub(text, func) {
      let _this = this
      this.$confirm({
        title: '温馨提示',
        content: text,
        onOk: () => {
          return func()
        },
        onCancel() {}
      })
    },
    add() {
      const curUser = this.rowSelection.selectedRows[0]
      const param = {
        youthOrgId: this.curOption.id,
        userId: curUser.userId,
        userName: curUser.name,
        phone: curUser.phoneNum,
        employeeNum: curUser.jobNum,
        status: 1,
        ...this.addForm
      }
      this.addFormoading = true
      return addYouthMember(param)
        .then((res) => {
          this.addFormoading = false
          if (res && res.code == 0) {
            this.$message.success('添加成功')
            this.handleCancel()
            this.$emit('submitSuccess')
          } else {
            this.$message.error('添加失败！')
          }
        })
        .catch(() => {
          this.addFormoading = false
        })
    },
    submitForm() {
      if (this.rowSelection.selectedRowKeys.length == 0) {
        this.$message.error('请先选择员工！')
        return
      }
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.confirmSub('确认提交吗？', this.add)
        } else {
          return false
        }
      })
    }
  },
  watch: {
    visible(e) {
      if (e) {
        this.needTree &&
          !this.$refs.treeOrganization &&
          this.$nextTick(() => {
            this.$refs.treeOrganization.getList()
          })
        this.$nextTick(() => {
          this.$refs.addForm.resetFields()
          this.rowSelection.selectedRows = []
          this.$refs.table.refresh(true)
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.member-search {
  /deep/ .ant-advanced-search-form .ant-form-item {
    margin-bottom: 4px;
  }
}
.ant-form-item {
  display: flex;
}
.ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}
</style>